﻿using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using System.Text.Json;


namespace WpfWebSocketApp
{
    public partial class MainWindow : Window
    {
        private ClientWebSocket _webSocket;
        private Uri _serverUri = new Uri("ws://127.0.0.1:8080"); // 替换为你的服务器地址和端口

        public MainWindow()
        {
            InitializeComponent();
        }

        private async void ConnectButton_Click(object sender, RoutedEventArgs e)
        {
            _webSocket = new ClientWebSocket();
            try
            {
                await _webSocket.ConnectAsync(_serverUri, CancellationToken.None);
                if (_webSocket.State == WebSocketState.Open)
                {
                    MessageBox.Show("WebSocket 连接成功！");
                    // 启动接收消息的后台任务
                    Task.Run(() => ReceiveMessagesAsync());
                }
                else
                {
                    MessageBox.Show($"WebSocket 连接失败，状态: {_webSocket.State}");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"连接错误: {ex.Message}");
            }
        }

        private async void SendButton_Click(object sender, RoutedEventArgs e)
        {
            if (_webSocket != null && _webSocket.State == WebSocketState.Open)
            {
                string messageToSend = MessageTextBox.Text;
                byte[] buffer = Encoding.UTF8.GetBytes(messageToSend);
                try
                {
                    await _webSocket.SendAsync(new ArraySegment<byte>(buffer), WebSocketMessageType.Text, true, CancellationToken.None);
                    // Optionally clear the input box
                    MessageTextBox.Clear();
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"发送消息错误: {ex.Message}");
                }
            }
            else
            {
                MessageBox.Show("WebSocket 连接尚未打开！");
            }
        }

        private async Task ReceiveMessagesAsync()
        {
            byte[] buffer = new byte[1024];
            while (_webSocket != null && _webSocket.State == WebSocketState.Open)
            {
                try
                {
                    WebSocketReceiveResult result = await _webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
                    if (result.MessageType == WebSocketMessageType.Text)
                    {
                        string receivedMessage = Encoding.UTF8.GetString(buffer, 0, result.Count);
                        Dispatcher.Invoke(() =>
                        {
                            // Update UI element (e.g., a ListBox to display messages)
                            MessageList.Items.Add($"接收到: {receivedMessage}");
                        });
                    }
                    else if (result.MessageType == WebSocketMessageType.Close)
                    {
                        Dispatcher.Invoke(() => MessageBox.Show("服务器关闭了连接。"));
                        await _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
                        break;
                    }
                }
                catch (Exception ex)
                {
                    Dispatcher.Invoke(() => MessageBox.Show($"接收消息错误: {ex.Message}"));
                    break;
                }
            }
        }

        private async void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (_webSocket != null && _webSocket.State == WebSocketState.Open)
            {
                await _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "客户端关闭", CancellationToken.None);
            }
            _webSocket?.Dispose();
        }
    }
}